package net.ak.dao.impl;

import java.util.List;

import net.ak.dao.UserDao;
import net.ak.model.User;
import net.ak.model.UserCategory;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl extends BaseDao<User> implements UserDao {

	@Override
	public boolean login(String username, String password) {
		Session session 	= sessionFactory.openSession();
		Criteria  criteria 	= session.createCriteria(User.class);
		criteria.add(Restrictions.eq("username", username));
		criteria.add(Restrictions.eq("password", password));
		session.close();
		
		return criteria.list().size() > 0;
	}

	@Override
	@SuppressWarnings("unchecked")
	public List<User> listUsers() {
		Session session 	= sessionFactory.openSession();
		Criteria  criteria 	= session.createCriteria(User.class);
		List<User> users 	= criteria.list();
		session.close();
		
		return users;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> listUsersByCategory(List<UserCategory> categories) {
		Session session 	= sessionFactory.openSession();
		Criteria  criteria 	= session.createCriteria(User.class);
		for (UserCategory category : categories) {
			criteria.add(Restrictions.or(Restrictions.eq("id", category.getUser().getId())));
		}
		List<User> users 	= criteria.list();
		session.close();
		return users;
	}

	@Override
	public User getUserByEmail(String email) {
		Session session 	= sessionFactory.openSession();
		Criteria  criteria 	= session.createCriteria(User.class).add(Restrictions.eq("email", email));
		@SuppressWarnings("unchecked")
		List<User> users 	= criteria.list();
		session.close();
		return  users.size() > 0 ? (User)users.get(0) : null; 
	}

	@Override
	public User getUserByEmailAndPassword(String email, String password) {
		Session session 	= sessionFactory.openSession();
		Criteria  criteria 	= session.createCriteria(User.class).add(Restrictions.eq("email", email)).add(Restrictions.eq("password", password));
		@SuppressWarnings("unchecked")
		List<User> users 	= criteria.list();
		session.close();
		return  users.size() > 0 ? users.get(0) : null; 
	}

}
